/**
 * AbstractHQLCreator.java
 * 卢晓峰
 * Email：lxf9601@gmail.com
 * QQ：297051898
 * Created by 2010-7-18
 */
package com.autoabacus.core.config.provider.creator;

import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.autoabacus.core.config.component.Field;
import com.autoabacus.core.config.component.Table;
import com.autoabacus.core.config.exception.FieldNotFoundException;
import com.autoabacus.core.config.protocol.FieldProtocol.QueryStrategy;
import com.autoabacus.core.config.provider.HQLCreator;
import com.autoabacus.core.config.provider.QuerySource;
import com.autoabacus.core.config.provider.SqlOperateChar;
import com.autoabacus.core.util.StringUtils;

/**
 * hql创建基类,实现了where条件封装
 * addWhereSlice(Table table, Map<String, Object> parameter)
 * @author 卢晓峰
 */
public abstract class AbstractHQLCreator implements HQLCreator {
	
	protected Logger log = LoggerFactory.getLogger(this.getClass());
	public static final String BETWEEN_SPLIT_CHAR = ",";
	
	/**
	 * 添加where条件语句
	 * @param table
	 * @param querySource
	 * @param parameter
	 * @param hql
	 */
	public void addWhereSlice(Table table, QuerySource querySource, StringBuffer hql) {
		if (querySource.getParameters().size() > 0) {
			hql.append(" where");
			for (Entry<String, Object> entry : querySource.getParameters().entrySet())
			{
				Field field = table.getFields().get(entry.getKey());
				if (field == null) {
					log.error("字段{}不存在于配置信息中", entry.getKey());
					throw new FieldNotFoundException("字段" + entry.getKey() + "不存在于配置信息中");
				}
					
				hql.append(" ");
				hql.append(field.getName());
				hql.append(" ");
				if (field.getQueryStrategy().name().endsWith("_EXACT")) {
					// 精确匹配
					hql.append(SqlOperateChar.OPER_EQ);
					hql.append(" ");
					hql.append(entry.getValue().toString());
				} else if (field.getQueryStrategy() == QueryStrategy.STRING_LIKE) {
					// 模糊匹配
					hql.append(SqlOperateChar.OPER_LIKE);
					hql.append(" ");
					hql.append(entry.getValue().toString());
				} else if (field.getQueryStrategy().name().endsWith("_MULTI")) {
					// 多个匹配
					hql.append(SqlOperateChar.OPER_IN);
					hql.append(" ");
					hql.append("(");
					hql.append(entry.getValue().toString());
					hql.append(")");
				} else
				{
					// 范围查询条件
					String[] betweenValues = entry.getValue().toString().split(BETWEEN_SPLIT_CHAR);
					if (StringUtils.hasText(betweenValues[0])) {
						hql.append(SqlOperateChar.OPER_QE);
						hql.append(" ");
						hql.append(betweenValues[0]);
						hql.append(" and");
					}
					
					if (StringUtils.hasText(betweenValues[1])) {
						hql.append(" ");
						hql.append(field.getName());
						hql.append(" ");
						hql.append(SqlOperateChar.OPER_LE);
						hql.append(" ");
						hql.append(betweenValues[1]);
					}
				}
				
				hql.append(" and");
			}
			
			hql.delete(hql.length() - 4, hql.length());
		}
	}
}
